package com.cxm.qyyz.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.ref.WeakReference;

/**
 * author : yzx
 * Time   :2022/2/8
 * desc   :
 */
public class AutoPollRecyclerViewLeft extends RecyclerView {

    private int TIME_AUTO_POLL = 10;
    AutoPollTask autoPollTask;
    private boolean running; //表示是否正在自动轮询
    private boolean canRun;//表示是否可以自动轮询
    private int  w;//表示是否可以自动轮询


    public AutoPollRecyclerViewLeft(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        autoPollTask = new AutoPollTask(this);
    }

    static class AutoPollTask implements Runnable {
        private final WeakReference<AutoPollRecyclerViewLeft> mReference;

        //使用弱引用持有外部类引用->防止内存泄漏
        public AutoPollTask(AutoPollRecyclerViewLeft reference) {
            this.mReference = new WeakReference<AutoPollRecyclerViewLeft>(reference);
        }

        @Override
        public void run() {
            AutoPollRecyclerViewLeft recyclerView = mReference.get();
            if (recyclerView.autoPollTask == null )return;
            if (recyclerView.running && recyclerView.canRun) {
                recyclerView.smoothScrollBy(recyclerView.w, 0);
                recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.TIME_AUTO_POLL);
            }

        }
    }

    //开启:如果正在运行,先停止->再开启
    public void start(int w) {

        if (running)
            stop(-1);
        TIME_AUTO_POLL = 20;
        canRun = true;
        if (w!=-1){

            this. w = w;
        }
        running = true;
        if (null == autoPollTask)return;
        postDelayed(autoPollTask, TIME_AUTO_POLL);
    }

    //开启:如果正在运行,先停止->再开启
    public void start(int w,int time) {
        if (running)
            stop(-1);
        TIME_AUTO_POLL = time;
        canRun = true;
        if (w!=-1){
            this. w = w;
        }
        running = true;
        if (null == autoPollTask)return;
        postDelayed(autoPollTask, TIME_AUTO_POLL);
    }


    public void onDestroy() {
        removeCallbacks(autoPollTask);
        autoPollTask = null;
    }

    public void stop(int position) {
        if (position == -1) {
            return;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (running)
                    stop(-1);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                if (canRun)
                    start(-1);
                break;
        }
        return super.onTouchEvent(e);
    }
}
